package com.eden.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.eden.common.R;
import com.eden.dto.TagDto;
import com.eden.entity.Tag;
import com.eden.mapper.TagMapper;
import com.eden.service.TagService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Service
public class TagServiceImpl implements TagService {
    @Autowired
    private TagMapper tagMapper;

    private TagDto copy(Tag tag) {
        TagDto tagDto = new TagDto();
        BeanUtils.copyProperties(tag, tagDto);
        return tagDto;
    }

    private List<TagDto> copyList(List<Tag> tagList) {
        List<TagDto> tagDtoList = new ArrayList<>();
        for (Tag tag : tagList) {
            tagDtoList.add(copy(tag));
        }
        return tagDtoList;

    }

    @Override
    public List<TagDto> findTagsByArticleId(Long articleId) {
        //mybatisplus无法多表查询
        List<Tag> tags = tagMapper.findTagsByArticleId(articleId);
        return copyList(tags);
    }

    @Override
    public R hots(int limit) {
        //标签下文章最多的是最热标签，前limit个
        List<Long> tagIds = tagMapper.findHotsTagIds(limit);
        if (CollectionUtils.isEmpty(tagIds)) {
            return R.success(Collections.emptyList());
        }
        //需求的是tagId和tagName Tag.对象
        //select from tag where id in (1,2,3,4)
        List<Tag> tagList = tagMapper.findTagsByTagIds(tagIds);

        return R.success(tagList);
    }

    @Override
    public R findAll() {
        List<Tag> tags = this.tagMapper.selectList(new LambdaQueryWrapper<>());
        return R.success(copyList(tags));
    }

    @Override
    public R findAllDetail() {
        LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<>();
        List<Tag> tags = this.tagMapper.selectList(queryWrapper);
        return R.success(copyList(tags));
    }



}
